package com.kaiwukj.android.ufamily.mvp.ui.page.service.gm;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerServiceComponent;
import com.kaiwukj.android.ufamily.di.module.ServiceModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.GMProjectMemberResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.GMAppointmentOrderResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.GMOrderDetailResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.GMOrderResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.ServiceContract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.GridSpaceItemDecoration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterUrlKt.OrderGMDetailUrl)
public class GMOrderDetailActivity extends BaseMvpActivity<GMOrderPresenter> implements ServiceContract.GMOrderView {

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.container_project_info)
    ViewGroup containerProjectInfo;//项目信息
    @BindView(R.id.tv_project_info_name)
    TextView tvProjectInfoName;//项目名称
    @BindView(R.id.tv_project_info_startdate)
    TextView tvProjectInfoStartDate;//开工日期
    @BindView(R.id.tv_project_info_enddate)
    TextView tvProjectInfoEndDate;//完工日期
    @BindView(R.id.tv_project_info_stage)
    TextView tvProjectInfoState;//项目阶段

    @BindView(R.id.container_video)
    ViewGroup containerVideo;

    @BindView(R.id.container_content)
    ViewGroup containerContent;

    @BindView(R.id.container_project_member)
    ViewGroup containerProjectMember;//项目成员
    @BindView(R.id.rv_project_member)
    RecyclerView rvProjectMember;

    @BindView(R.id.container_order_info)
    ViewGroup containerOrderInfo;//订单信息
    @BindView(R.id.tv_order_no)
    TextView tvOrderNo;//订单编号
    @BindView(R.id.tv_order_customer_name)
    TextView tvOrderCustomerName;//客户名称
    @BindView(R.id.tv_order_contract)
    TextView tvOrderContract;//联系电话
    @BindView(R.id.tv_order_amount)
    TextView tvOrderAmount;//订单金额

    @BindView(R.id.container_order_contract)
    ViewGroup containerOrderContract;//合同信息
    @BindView(R.id.tv_order_deposit_amount)
    TextView tvOrderDepositAmount;//定金金额
    @BindView(R.id.tv_order_rest_amount)
    TextView tvOrderRestAmount;//尾款金额
    @BindView(R.id.tv_order_contract_pre)
    TextView tvOrderContractPre;//预定合同
    @BindView(R.id.tv_order_contract_pre_view)
    TextView tvOrderContractPreView;//预定合同预览
    @BindView(R.id.tv_order_contract_formal)
    TextView tvOrderContractFormal;//正式合同
    @BindView(R.id.tv_order_contract_formal_view)
    TextView tvOrderContractFormalView;//正式合同预览

    @BindView(R.id.container_order_annex)
    ViewGroup containerOrderAnnex;//附件信息
    @BindView(R.id.rv_huxing)
    RecyclerView rvHuxing;//户型图
    @BindView(R.id.rv_design)
    RecyclerView rvDesign;//设计效果图
    @BindView(R.id.tv_house_3d_pre)
    TextView tvHouse3DPre;//查看3D效果图

    @BindView(R.id.container_order_annex_other)
    ViewGroup containerOrderAnnexOther;//其他附件
    @BindView(R.id.rv_annex_other)
    RecyclerView rvAnnexOther;


    @Autowired
    int orderId;
    @Autowired
    String title;

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerServiceComponent.builder()
                .appComponent(appComponent)
                .serviceModule(new ServiceModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_gm_order_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvTitle.setText(title);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mPresenter.fetchGMOrderDetail(orderId);
    }

    private void initUI(GMOrderDetailResult result) {
        tvProjectInfoName.setText(result.getProjectName());
        tvProjectInfoStartDate.setText(result.getStartDate());
        tvProjectInfoEndDate.setText(result.getCompletionDate());
        tvProjectInfoState.setText(result.getProjectPhaseStr());

        if (result.getDeviceVOList() == null || result.getDeviceVOList().isEmpty()) {
            containerVideo.setVisibility(View.GONE);
        } else {
            containerVideo.setVisibility(View.VISIBLE);
            containerVideo.setOnClickListener(v -> ARouter.getInstance().build(ARouterUrlKt.OrderGMVideoUrl)
                    .withSerializable("result", result)
                    .navigation());
        }

        initProjectMember(result);

        tvOrderNo.setText(result.getProjectOrderNum());
        tvOrderCustomerName.setText(result.getCustomerName());
        tvOrderContract.setText(result.getCustomerPhone());
        tvOrderAmount.setText(String.format("¥%s", result.getOrderAmount()));

        tvOrderDepositAmount.setText(String.format("¥%s", result.getFrontMoneyAmount()));
        tvOrderRestAmount.setText(String.format("¥%s", result.getFinalPaymentAmount()));
        tvOrderContractPre.setText(result.getScheduledContractNo());
        tvOrderContractPreView.setOnClickListener(v -> browserFile(result.getScheduledContractPDF(), false));
        if (StringUtils.isEmpty(result.getScheduledContractPDF())) {
            tvOrderContractPreView.setVisibility(View.GONE);
        } else {
            tvOrderContractPreView.setVisibility(View.VISIBLE);
        }
        tvOrderContractFormal.setText(result.getOfficialContractNo());
        tvOrderContractFormalView.setOnClickListener(v -> browserFile(result.getOfficialContractPDF(), false));
        if (StringUtils.isEmpty(result.getOfficialContractPDF())) {
            tvOrderContractFormalView.setVisibility(View.GONE);
        } else {
            tvOrderContractFormalView.setVisibility(View.VISIBLE);
        }

        showHuxingImgs(result.getApartmentRenderings());
        showDesignImgs(result.getDesignSketch());

        tvHouse3DPre.setVisibility(StringUtils.isEmpty(result.getDesignSketchUrl()) ? View.GONE : View.VISIBLE);
        tvHouse3DPre.setOnClickListener(v -> {
            browserFile(result.getDesignSketchUrl(), true);
        });

        showOtherAnnex(result.getOtherAccessories());
    }

    private void initProjectMember(GMOrderDetailResult result) {
        List<GMProjectMemberResult> memberResults = new ArrayList<>();
        if (!StringUtils.isEmpty(result.getProjectManagerName())) {
            memberResults.add(new GMProjectMemberResult(result.getProjectManagerName(),
                    result.getProjectManagerHeadImg(),
                    "项目经理",
                    result.getProjectManagerPhone()));
        }
        if (!StringUtils.isEmpty(result.getSupervisorName())) {
            memberResults.add(new GMProjectMemberResult(result.getSupervisorName(),
                    result.getSupervisorHeadImg(),
                    "施工监理",
                    result.getSupervisorPhone()));
        }
        if (!StringUtils.isEmpty(result.getDesignerName())) {
            memberResults.add(new GMProjectMemberResult(result.getDesignerName(),
                    result.getDesignerHeadImg(),
                    "设计师",
                    result.getDesignerPhone()));
        }
        if (memberResults.size() == 0) {
            containerProjectMember.setVisibility(View.GONE);
        } else {
            containerProjectMember.setVisibility(View.VISIBLE);
            rvProjectMember.setLayoutManager(new LinearLayoutManager(this));
            GMProjectMemberAdapter memberAdapter = new GMProjectMemberAdapter(memberResults);
            rvProjectMember.setAdapter(memberAdapter);
            memberAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_call) {
                    String phone = memberAdapter.getItem(position).getPhone();
                    if (StringUtils.isEmpty(phone)) return;
                    showMessageOKCancel(this, String.format("电话:%s", phone), v -> {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse(String.format("tel:%s", phone)));
                        startActivity(intent);
                    });
                }
            });

        }
    }

    private void showHuxingImgs(String img) {
        if (StringUtils.isEmpty(img)) {
            return;
        }
        List<String> list = Arrays.asList(img.split(","));
        rvHuxing.setLayoutManager(new GridLayoutManager(this, 3));
        if (rvHuxing.getItemDecorationCount() == 0) {
            rvHuxing.addItemDecoration(new GridSpaceItemDecoration(5, 5));
            rvHuxing.setAdapter(new GMProjectImagePreviewAdapter(list));
        }
    }

    private void showDesignImgs(String img) {
        if (StringUtils.isEmpty(img)) {
            return;
        }
        List<String> list = Arrays.asList(img.split(","));
        rvDesign.setLayoutManager(new GridLayoutManager(this, 3));
        if (rvDesign.getItemDecorationCount() == 0) {
            rvDesign.addItemDecoration(new GridSpaceItemDecoration(5, 5));
            rvDesign.setAdapter(new GMProjectImagePreviewAdapter(list));
        }

    }

    private void showOtherAnnex(String path) {
        if (StringUtils.isEmpty(path)) {
            containerOrderAnnexOther.setVisibility(View.GONE);
            return;
        }
        List<String> list = Arrays.asList(path.split(","));
        rvAnnexOther.setLayoutManager(new LinearLayoutManager(this));
        rvAnnexOther.setAdapter(new GMProjectAnnexOtherAdapter(list));

    }

    private void browserFile(String url, boolean isLocal) {
        if (isLocal) {
            ARouter.getInstance().build(ARouterUrlKt.GMFilePreviewUrl)
                    .withString("url", url)
                    .navigation();
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
        }
    }

    @Override
    public void onFetchGMOrder(List<GMOrderResult> results) {

    }

    @Override
    public void onFetchGMAppointmentOrder(List<GMAppointmentOrderResult> results) {

    }

    @Override
    public void onGetOrderDetail(GMOrderDetailResult result) {
        initUI(result);
    }
}
